// pages/needHelp/index/index.js
import requestUtil from "../../../api/request"
import API from "../../../api/http.api"

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideHomeButton()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("h-index---------------------onShow");
    this.checkAllDeviceAuthorize();
    this.isJumpingPage = false;
    // this.makeAppointment()
  },

  /**
   * 呼叫志援者
   */
  callVolunteerNow: function(e) {
    var that = this
    if (that.isJumpingPage == false) {
      that.isJumpingPage = true
      requestUtil.post(API.CREATE_VIDEO_CALL, {})
        .then((res) => {
          console.log(res)
          app.globalData.userSig = res.data.userSig
          const url = `../../room/room?userID=${app.globalData.openId}&roomID=${res.data.roomID}&callId=${res.data.callId}&cloudenv=${that.data.cloudenv}&frontCamera=back`
          wx.navigateTo({ url: url })
          that.isJumpingPage = false
        }).catch((err) => {
          that.isJumpingPage = false
        })
    }
  },

  /**
   * 跳转预约的各个界面
   */
  makeAppointment: function(e) {
    var that = this
    // 防止多次快速点击后多次打开页面
    if (that.isJumpingPage == false) {
      that.isJumpingPage = true
      // wx.navigateTo({
      //   url: '../appointment/appointment'
      // })

      // 检查预约情况
      requestUtil.post(API.UNCOMPLETED_APPOINTMENT, {
        'userType': app.globalData.userType
      }).then(res => {
        var data = res.data
        console.log("查询预约：")
        console.log(data)
        // 有预约但无人处理
        if (data.msgStatus == 0) {
          wx.navigateTo({
            url: `../wait/wait?id=${data.id}&content=${data.content}`
          })
        } else {
          // 有预约并且有人接受
          wx.navigateTo({
            url: `../handle/handle?id=${data.id}&content=${data.content}&handleUserOpenId=${data.handleUserOpenId}`
          })
        }
      }).catch((err) => {
        console.log(err)
        // 没有预约
        if (err.code === 20001) {
          wx.navigateTo({
            url: '../create/create'
          })
        }else{
          // 出错
          that.isJumpingPage = false
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 检查麦克风摄像头权限
   */
  checkAllDeviceAuthorize: function() {
    var that = this;
    wx.getSetting({
      withSubscriptions: true,
    }).then((result) => {
      console.log('getSetting', result);
      that.authorizeMic = result.authSetting['scope.record']
      that.authorizeCamera = result.authSetting['scope.camera']
      // 检查麦克风，摄像头权限
      if (that.authorizeMic && that.authorizeCamera) {
        console.log("已通过所有授权");
        return;
      }
      that.checkMicAuthorize();
    });
  },

  /**
   * 授权麦克风
   */
  checkMicAuthorize: function() {
    var that = this
    wx.authorize({
      scope: 'scope.record',
    }).then((res) => {
      console.log('authorize mic', res)
      //   that.authorizeMic = true
      that.checkCameraAuthorize()
    }).catch((error) => {
      console.log('authorize mic error', error)
      //   that.authorizeMic = false
      if (error.errMsg == "authorize:fail auth cancel") {
        // 点击返回键取消了授权
        that.checkAllDeviceAuthorize()
      } else {
        that.openConfirm('您没有打开麦克风权限，将无法使用小程序', '去打开', 'record')
      }
    })
  },

  /**
   * 授权摄像头
   */
  checkCameraAuthorize: function() {
    var that = this
    wx.authorize({
      scope: 'scope.camera',
    }).then((res) => {
      console.log('authorize camera', res)
      // that.authorizeCamera = true
    }).catch((error) => {
      console.log('authorize camera error', error)
      // that.authorizeCamera = false
      if (error.errMsg == "authorize:fail auth cancel") {
        // 点击返回键取消了授权
        that.checkCameraAuthorize()
      } else {
        that.openConfirm('您没有打开摄像头权限，将无法使用小程序', '去打开', 'camera')
      }
    })
  },

  openConfirm: function(content, confirmText, authType) {
    var that = this
    if (this.hasOpenDeviceAuthorizeModal) {
      return
    }
    this.hasOpenDeviceAuthorizeModal = true
    return wx.showModal({
      title: '授权申请',
      content: content,
      confirmText: confirmText,
      showCancel: false,
      success: (res) => {
        this.hasOpenDeviceAuthorizeModal = false
        console.log(res)
        // 点击“确认”时打开设置页面
        if (res.confirm) {
          if (authType == 'subMsg-o') {
            wx.requestSubscribeMessage({
              tmplIds: ['V2N215C6c8dAg4qUxlZShk8VzxijNnRGUWop1BvB9Qo'],
              success(res) {}
            })
          } else {
            wx.openSetting({
              success: (res) => {},
            })
          }
        } else {
          console.log('用户点击取消')
          if (authType == 'record') {
            that.checkMicAuthorize()
          } else if (authType == 'camera') {
            that.checkCameraAuthorize()
          } else if (authType == 'userLocationBackground') {
            that.checkBackgroundLocationAuthorize()
          } else if (authType == 'subMsg' || authType == 'subMsg-o') {
            that.checkSubMsgAuthorize()
          }
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})